package guanli;

import until.DBUtil;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;
import java.util.Random;

public class AdminManagePanel extends JPanel {
    private JTable table;
    private DefaultTableModel model;

    public AdminManagePanel() {
        setLayout(new BorderLayout());

        model = new DefaultTableModel(new Object[]{"ID", "用户名", "电话", "角色"}, 0);
        table = new JTable(model);
        add(new JScrollPane(table), BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel();
        JButton deleteButton = new JButton("删除管理员");
        JButton updateButton = new JButton("修改管理员");
        JButton refreshButton = new JButton("刷新"); // 添加刷新按钮
        buttonPanel.add(deleteButton);
        buttonPanel.add(updateButton);
        buttonPanel.add(refreshButton); // 将刷新按钮加入面板
        add(buttonPanel, BorderLayout.SOUTH);

        loadAdmins();

        deleteButton.addActionListener(e -> deleteAdmin());
        updateButton.addActionListener(e -> updateAdmin());
        refreshButton.addActionListener(e -> loadAdmins()); // 绑定刷新事件
    }

    private void loadAdmins() {
        model.setRowCount(0);
        try (Connection conn = DBUtil.getConnection()) {
            String sql = "SELECT id, username, phone, role FROM users WHERE role = '管理员'";
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                model.addRow(new Object[]{
                        rs.getInt("id"),
                        rs.getString("username"),
                        rs.getString("phone"),
                        rs.getString("role")
                });
            }
            rs.close();
            ps.close();
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "加载管理员失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void deleteAdmin() {
        int row = table.getSelectedRow();
        if (row == -1) {
            JOptionPane.showMessageDialog(this, "请先选择一个管理员。", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        int id = (int) model.getValueAt(row, 0);
        String phone = (String) model.getValueAt(row, 2);

        if (!verifyWithCode(phone)) return;

        int confirm = JOptionPane.showConfirmDialog(this, "确定要删除该管理员吗？", "确认", JOptionPane.YES_NO_OPTION);
        if (confirm == JOptionPane.YES_OPTION) {
            try (Connection conn = DBUtil.getConnection()) {
                String sql = "DELETE FROM users WHERE id = ?";
                PreparedStatement ps = conn.prepareStatement(sql);
                ps.setInt(1, id);
                ps.executeUpdate();
                ps.close();
                JOptionPane.showMessageDialog(this, "删除成功！");
                loadAdmins();
            } catch (Exception e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(this, "删除失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private void updateAdmin() {
        int row = table.getSelectedRow();
        if (row == -1) {
            JOptionPane.showMessageDialog(this, "请先选择一个管理员。", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        int id = (int) model.getValueAt(row, 0);
        String currentUsername = (String) model.getValueAt(row, 1);
        String currentPhone = (String) model.getValueAt(row, 2);

        if (!verifyWithCode(currentPhone)) return;

        String newUsername = JOptionPane.showInputDialog(this, "输入新用户名：", currentUsername);
        String newPhone = JOptionPane.showInputDialog(this, "输入新电话：", currentPhone);

        if (newUsername == null || newPhone == null || newUsername.trim().isEmpty() || newPhone.trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "输入无效。", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        try (Connection conn = DBUtil.getConnection()) {
            String sql = "UPDATE users SET username = ?, phone = ? WHERE id = ?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, newUsername.trim());
            ps.setString(2, newPhone.trim());
            ps.setInt(3, id);
            ps.executeUpdate();
            ps.close();
            JOptionPane.showMessageDialog(this, "修改成功！");
            loadAdmins();
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "修改失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    // 模拟验证码发送和验证
    private boolean verifyWithCode(String phone) {
        String code = generateCode();
        // 模拟“发送验证码”
        JOptionPane.showMessageDialog(this, "验证码已发送到手机号：" + phone + "\n（模拟验证码：" + code + "）", "验证码", JOptionPane.INFORMATION_MESSAGE);
        String input = JOptionPane.showInputDialog(this, "请输入收到的验证码：");
        if (input == null || !input.equals(code)) {
            JOptionPane.showMessageDialog(this, "验证码错误，操作取消。", "验证失败", JOptionPane.WARNING_MESSAGE);
            return false;
        }
        return true;
    }

    private String generateCode() {
        Random rand = new Random();
        int code = 100000 + rand.nextInt(900000);
        return String.valueOf(code);
    }
}